package com.hospital.workstation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospital.common.core.domain.entity.SysDept;
import com.hospital.common.utils.StringUtils;
import com.hospital.common.core.page.TableDataInfo;
import com.hospital.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hospital.system.mapper.SysDeptMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.hospital.workstation.domain.bo.HisChangeDepartmentBo;
import com.hospital.workstation.domain.vo.HisChangeDepartmentVo;
import com.hospital.workstation.domain.HisChangeDepartment;
import com.hospital.workstation.mapper.HisChangeDepartmentMapper;
import com.hospital.workstation.service.IHisChangeDepartmentService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 转科信息Service业务层处理
 *
 * @author whb
 * @date 2023-03-08
 */
@RequiredArgsConstructor
@Service
public class HisChangeDepartmentServiceImpl implements IHisChangeDepartmentService {

    private final HisChangeDepartmentMapper baseMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 查询转科信息
     */
    @Override
    public HisChangeDepartmentVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询转科信息列表
     */
    @Override
    public TableDataInfo<HisChangeDepartmentVo> queryPageList(HisChangeDepartmentBo bo, PageQuery pageQuery) {
        // 查询转科信息列表
        QueryWrapper<HisChangeDepartment> qw = buildQueryWrapper2(bo);
        Page<HisChangeDepartmentVo> result = baseMapper.selectVoPageCustomer(pageQuery.build(), qw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询转科信息列表
     */
    @Override
    public List<HisChangeDepartmentVo> queryList(HisChangeDepartmentBo bo) {
        // 获取HIS科室代码
        if (StringUtils.isNotBlank(bo.getDeptCode())) {
            // TODO 根据药历系统科室ID查询HIS科室代码
        }
        LambdaQueryWrapper<HisChangeDepartment> lqw = buildQueryWrapper(bo);
        // lqw.select(HisChangeDepartment::getDeptCode, HisChangeDepartment::getChangeIntoTime, HisChangeDepartment::getChangeOutTime);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HisChangeDepartment> buildQueryWrapper(HisChangeDepartmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HisChangeDepartment> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMedicalRecordNo() != null, HisChangeDepartment::getMedicalRecordNo, bo.getMedicalRecordNo());
        lqw.eq(StringUtils.isNotBlank(bo.getDeptCode()), HisChangeDepartment::getDeptCode, bo.getDeptCode());
        lqw.eq(bo.getChangeIntoTime() != null, HisChangeDepartment::getChangeIntoTime, bo.getChangeIntoTime());
        lqw.eq(StringUtils.isNotBlank(bo.getTargDocCode()), HisChangeDepartment::getTargDocCode, bo.getTargDocCode());
        lqw.eq(StringUtils.isNotBlank(bo.getTargWardCode()), HisChangeDepartment::getTargWardCode, bo.getTargWardCode());
        lqw.eq(StringUtils.isNotBlank(bo.getTargRoomCode()), HisChangeDepartment::getTargRoomCode, bo.getTargRoomCode());
        lqw.eq(StringUtils.isNotBlank(bo.getTargBedCode()), HisChangeDepartment::getTargBedCode, bo.getTargBedCode());
        lqw.eq(bo.getChangeOutTime() != null, HisChangeDepartment::getChangeOutTime, bo.getChangeOutTime());
        lqw.eq(StringUtils.isNotBlank(bo.getOrigDocCode()), HisChangeDepartment::getOrigDocCode, bo.getOrigDocCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrigWardCode()), HisChangeDepartment::getOrigWardCode, bo.getOrigWardCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrigRoomCode()), HisChangeDepartment::getOrigRoomCode, bo.getOrigRoomCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrigBedCode()), HisChangeDepartment::getOrigBedCode, bo.getOrigBedCode());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null, HisChangeDepartment::getChangeIntoTime,
            params.get("beginTime") + " 00:00:00", params.get("endTime") + " 23:59:59");
        lqw.orderByDesc(HisChangeDepartment::getChangeIntoTime);
        return lqw;
    }

    private QueryWrapper<HisChangeDepartment> buildQueryWrapper2(HisChangeDepartmentBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<HisChangeDepartment> qw = Wrappers.query();
        qw.eq(bo.getMedicalRecordNo() != null, "hcd.medical_record_no", bo.getMedicalRecordNo())
            .eq(StringUtils.isNotBlank(bo.getDeptCode()), "sd.dept_id", bo.getDeptCode())
            .between(params.get("beginTime") != null && params.get("endTime") != null, "hcd.change_into_time",
                params.get("beginTime") + " 00:00:00", params.get("endTime") + " 23:59:59")
            .orderByDesc("hcd.change_into_time");
        return qw;
    }

    /**
     * 新增转科信息
     */
    @Override
    public Boolean insertByBo(HisChangeDepartmentBo bo) {
        HisChangeDepartment add = BeanUtil.toBean(bo, HisChangeDepartment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改转科信息
     */
    @Override
    public Boolean updateByBo(HisChangeDepartmentBo bo) {
        // 查询更新转出时间的记录
        List<HisChangeDepartment> hisChangeDepartmentList = baseMapper.selectList(new LambdaQueryWrapper<HisChangeDepartment>()
            .eq(HisChangeDepartment::getMedicalRecordNo, bo.getMedicalRecordNo())
            .eq(StringUtils.isNotBlank(bo.getDeptCode()), HisChangeDepartment::getDeptCode, bo.getDeptCode())
            .orderByDesc(HisChangeDepartment::getChangeIntoTime));
        if (ObjectUtil.isNotNull(hisChangeDepartmentList) && hisChangeDepartmentList.size() > 0) {
            HisChangeDepartment hisChangeDepartment = hisChangeDepartmentList.get(0);
            if (hisChangeDepartment.getChangeOutTime() != null) {
                return true;
            }
            hisChangeDepartment.setChangeOutTime(bo.getChangeOutTime());
            hisChangeDepartment.setOrigDocCode(bo.getOrigDocCode());
            hisChangeDepartment.setOrigWardCode(bo.getOrigWardCode());
            hisChangeDepartment.setOrigRoomCode(bo.getOrigRoomCode());
            hisChangeDepartment.setOrigBedCode(bo.getOrigBedCode());
            return baseMapper.updateById(hisChangeDepartment) > 0;
        } else {
            return true;
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HisChangeDepartment entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除转科信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * His出院,查询最后转科记录
     *
     * @param medicalRecordNo
     * @return
     */
    @Override
    public HisChangeDepartmentVo selectByMedicalRecordNoAnd(int medicalRecordNo) {
        LambdaQueryWrapper<HisChangeDepartment> lqw = Wrappers.lambdaQuery();
        lqw.eq(HisChangeDepartment::getMedicalRecordNo, medicalRecordNo);
        lqw.isNull(HisChangeDepartment::getOrigBedCode);
        lqw.isNull(HisChangeDepartment::getOrigWardCode);
        lqw.isNull(HisChangeDepartment::getOrigRoomCode);
        lqw.orderByDesc(HisChangeDepartment::getCreateTime);
        List<HisChangeDepartmentVo> hisChangeDepartmentVos = baseMapper.selectVoList(lqw);
        if (hisChangeDepartmentVos.size() > 0) {
            return hisChangeDepartmentVos.get(0);
        } else {
            return null;
        }
    }
}
